// Copyright [2021] [Jorge C Leitao]
// Copyright 2021 Datafuse Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Contains [`Error`]

/// List of features whose non-activation may cause a runtime error.
/// Used to indicate which lack of feature caused [`Error::FeatureNotActive`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Feature {
    /// Snappy compression and decompression
    Snappy,
    /// Brotli compression and decompression
    Brotli,
    /// Gzip compression and decompression
    Gzip,
    /// Lz4 raw compression and decompression
    Lz4,
    /// Zstd compression and decompression
    Zstd,
}

/// Errors generated by this crate
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Error {
    /// When the parquet file is known to be out of spec.
    OutOfSpec(String),
    /// Error presented when trying to use a code branch that requires activating a feature.
    FeatureNotActive(Feature, String),
    /// Error presented when trying to use a feature from parquet that is not yet supported
    FeatureNotSupported(String),
    /// When encoding, the user passed an invalid parameter
    InvalidParameter(String),
    /// When decoding or decompressing, the page would allocate more memory than allowed
    WouldOverAllocate,
}

impl Error {
    pub(crate) fn oos<I: Into<String>>(message: I) -> Self {
        Self::OutOfSpec(message.into())
    }
}

impl std::error::Error for Error {}

impl std::fmt::Display for Error {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Error::OutOfSpec(message) => {
                write!(fmt, "File out of specification: {}", message)
            }
            Error::FeatureNotActive(feature, reason) => {
                write!(
                    fmt,
                    "The feature \"{:?}\" needs to be active to {}",
                    feature, reason
                )
            }
            Error::FeatureNotSupported(reason) => {
                write!(fmt, "Not yet supported: {}", reason)
            }
            Error::InvalidParameter(message) => {
                write!(fmt, "Invalid parameter: {}", message)
            }
            Error::WouldOverAllocate => {
                write!(fmt, "Operation would exceed memory use threshold")
            }
        }
    }
}

#[cfg(feature = "snappy")]
impl From<snap::Error> for Error {
    fn from(e: snap::Error) -> Error {
        Error::OutOfSpec(format!("underlying snap error: {}", e))
    }
}

#[cfg(feature = "lz4_flex")]
impl From<lz4_flex::block::DecompressError> for Error {
    fn from(e: lz4_flex::block::DecompressError) -> Error {
        Error::OutOfSpec(format!("underlying lz4_flex error: {}", e))
    }
}

#[cfg(feature = "lz4_flex")]
impl From<lz4_flex::block::CompressError> for Error {
    fn from(e: lz4_flex::block::CompressError) -> Error {
        Error::OutOfSpec(format!("underlying lz4_flex error: {}", e))
    }
}

impl From<parquet_format_safe::thrift::Error> for Error {
    fn from(e: parquet_format_safe::thrift::Error) -> Error {
        Error::OutOfSpec(format!("Invalid thrift: {}", e))
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Error {
        Error::OutOfSpec(format!("underlying IO error: {}", e))
    }
}

impl From<std::collections::TryReserveError> for Error {
    fn from(e: std::collections::TryReserveError) -> Error {
        Error::OutOfSpec(format!("OOM: {}", e))
    }
}

impl From<std::num::TryFromIntError> for Error {
    fn from(e: std::num::TryFromIntError) -> Error {
        Error::OutOfSpec(format!("Number must be zero or positive: {}", e))
    }
}

impl From<std::array::TryFromSliceError> for Error {
    fn from(e: std::array::TryFromSliceError) -> Error {
        Error::OutOfSpec(format!("Can't deserialize to parquet native type: {}", e))
    }
}

/// A specialized `Result` for Parquet errors.
pub type Result<T> = std::result::Result<T, Error>;
